package com.letv.android.client.view;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.letv.business.flow.PlayFlowEvents.FetchMetaEvent;
import com.letv.core.utils.LogInfo;

import org.greenrobot.eventbus.EventBus;

public class LetvPlayGestureLayout extends RelativeLayout implements OnGestureListener {

    /**
     * 无事件
     */
    public static final int NONE = 0x00;
    /**
     * 双指下划
     */
    public static final int DOUBLE_FINGERS_DOWN = 0x10;
    /**
     * 双指上划
     */
    public static final int DOUBLE_FINGERS_UP = 0x11;
    /**
     * 横划完成
     */
    public static final int LANDSCAPE_SCROLL_FINISH = 0x12;

    /**
     * 单指下划
     */
    public static final int SINGLE_FINGERS_DOWN = 0x13;

    /**
     * 单指上划
     */
    public static final int SINGLE_FINGERS_UP = 0x14;

    /**
     * 手势回调
     */
    protected LetvPlayGestureCallBack mCallbacks;

    /**
     * 当前手势事件
     */
    public int event;

    /**
     * 手势探测器
     */
    private GestureDetector mGestureDetector = null;

    /**
     * Y轴变化值，在一次事件完成后，会被归0
     */
    private float offsetY = 0;

    /**
     * X轴变化值，在一次事件完成后，会被归0
     */
    private float offsetX = 0;

    /**
     * 竖划斜率限制
     */
    private float portraitLimitSlope = 4; // 上下滑动手势的限制斜率

    /**
     * 横划斜率限制
     */
    private float landscapeLimitSlope = 1f / 4f; // 上下滑动手势的限制斜率

    /**
     * 方向锁
     */
    private int directionalLock = 0; // 0 无方向，1纵向，2横向

    /**
     * 双指上划伐值
     */
    private float doubleFingersUpCuttingValue = 0.3f;

    /**
     * 双指下划伐值
     */
    private float doubleFingersDownCuttingValue = 0.3f;

    /**
     * 屏幕两边上下滑动区域伐值
     */
    private float bothSidesCuttingValue = 0.5f;

    /**
     * 屏幕中间上下滑动区域伐值
     */
    private float middleCuttingValue = 0.5f;

    /**
     * 右半屏长度
     */
    private float rightProgerss = 0;

    /**
     * 左半屏长度
     */
    private float leftProgress = 0;

    /**
     * 横划进度记录
     */
    private float landscapeProgress = 0;

//    private LiveRoomModel mModel;

    private Context context;

    private long mDownTime;
    private float mX, mY;

    /**
     * 是否是全景
     */
    private boolean mIsPanorama = false;
    private LetvPanoramaGestureLayout mPanoramaController;

    public LetvPlayGestureLayout(Context activity, AttributeSet attrs) {
        super(activity, attrs);
        this.context = activity;
        init();
    }

    public LetvPlayGestureLayout(Context activity) {
        super(activity);
        this.context = activity;
        init();
    }

    public LetvPlayGestureLayout(Context activity, AttributeSet attrs, int defStyle) {
        super(activity, attrs, defStyle);
        this.context = activity;
        init();
    }

    public void setLetvPlayGestureCallBack(LetvPlayGestureCallBack callback, boolean isLive) {
        mCallbacks = callback;
        mPanoramaController = new LetvPanoramaGestureLayout(context, mCallbacks);
        // 是否是直播，直播音量和亮度手势区域是0.2
        if (isLive) {
            bothSidesCuttingValue = 0.2f;
        }
    }

    public void setIsPanorama(boolean isPanorama) {
        mIsPanorama = isPanorama;
    }

//    public void setModel(LiveRoomModel model) {
//        mModel = model;
//        bothSidesCuttingValue = 0.2f;
//    }

    /**
     * 是否使用自定义点击事件
     * 
     * @return
     */
    public boolean useCustomClick() {
        // return TextUtils.equals("SM-G9250", LetvUtils.getModelName()) || mModel != null;
        return true;
    }

    /**
     * 手势类内部初始化
     */
    protected void init() {
        mGestureDetector = new GestureDetector(this);
        mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {

            /**
             * 单击
             */
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if (useCustomClick()) {
                    if (mCallbacks != null) {
                        mCallbacks.onSingleTapUp();
                    }
                }

                return true;
            }

            /**
             * 双击
             */
            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                return false;
            }

            /**
             * 双击
             */
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                if (mCallbacks != null) {
                    mCallbacks.onDoubleTap();
                }
                //if(mModel != null){
                //    mModel.onDoubleTap();
                //}
                return true;
            }
        });
    }

    /**
     * 初始化页面空间，请再控件初始化后在调用
     */
    public void initializeData(float rightProgerss, float leftProgress) {
        this.rightProgerss = rightProgerss;
        this.leftProgress = leftProgress;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (mIsPanorama) {
            if (mPanoramaController != null) {
                mPanoramaController.onInterceptTouchEvent(ev);
            }
        }

        if (MotionEvent.ACTION_DOWN == ev.getAction()) {
            mDownTime = System.currentTimeMillis();
            mX = ev.getX();
            mY = ev.getY();
        }
        
        LogInfo.log("zhuqiao", "点击：x=" + mX + ";y=" + mY);

        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mIsPanorama) {
            if (mPanoramaController != null) {
                return mPanoramaController.onTouchEvent(event);
            }
        }

        if (MotionEvent.ACTION_DOWN == event.getAction()) {
            mDownTime = System.currentTimeMillis();
        } else if (MotionEvent.ACTION_UP == event.getAction()) {

            // 释放方向锁
            switch (this.event) {
                case DOUBLE_FINGERS_UP:
                    if (mCallbacks != null) {
                        mCallbacks.onDoubleFingersUp();
                    }
                    break;
                case DOUBLE_FINGERS_DOWN:
                    if (mCallbacks != null) {
                        mCallbacks.onDoubleFingersDown();
                    }
                    break;
                case LANDSCAPE_SCROLL_FINISH:
                    if (mCallbacks != null) {
                        mCallbacks.onLandscapeScrollFinish(landscapeProgress);
                    }
//                    if (mModel != null) {
//                        mModel.onLandscapeScrollFinish(landscapeProgress);
//                    }
                    break;
                case SINGLE_FINGERS_UP:
                    if (mCallbacks != null) {
                        mCallbacks.onMiddleSingleFingerUp();
                    }
//                    if (mModel != null) {
//                        mModel.onMiddleSingleFingerUp();
//                    }
                    break;
                case SINGLE_FINGERS_DOWN:
                    if (mCallbacks != null) {
                        mCallbacks.onMiddleSingleFingerDown();
                    }
                    break;
                default:
                    break;
            }

            this.directionalLock = 0;
            this.offsetY = 0;
            this.offsetX = 0;
            this.landscapeProgress = 0;
            this.event = NONE;

            if (mCallbacks != null) {
                mCallbacks.onTouchEventUp();
            }

            onTouchEventUp();

            //if (useCustomClick()) {
            //    if (System.currentTimeMillis() - mDownTime < 500) {
            //        if (Math.abs(mX - event.getX()) < 15 && Math.abs(mY - event.getY()) < 15) {
            //            // click
            //            LogInfo.log("zhuqiao", "new click");
            //            if (mCallbacks != null) {
            //                mCallbacks.onSingleTapUp();
            //            }
            //            doSingleTapUp();
            //        }
            //    }
            //}
        }
        return mGestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        leftProgress = 0;
        rightProgerss = 0;
        mOldBrightness = getBrightness();
        if (mCallbacks != null) {
            mCallbacks.onDown();
        }

//        if (mModel != null) {
//            mModel.setOldVolume(mModel.getCurSoundVolume());
//        }
        return true;
    }

    /**
     * 获得当前亮度
     * 
     * @return
     */
    public int getBrightness() {
        WindowManager.LayoutParams wl = ((Activity) context).getWindow().getAttributes();
        float br = wl.screenBrightness;
        LogInfo.log("clf", "getBrightness....br=" + br);
        if (br < 0) {
            br = 0.1f;
        }
        return (int) (br * 255);
    }

    private void setVolume(float incremental) {
//        if (mModel != null) {
//            int volume = mModel.getOldVolume();
//
//            int delta = (int) (mModel.getMaxSoundVolume() * incremental);
//            volume += delta;
//
//            if (volume < 0) {
//                volume = 0;
//            }
//
//            if (volume > mModel.getMaxSoundVolume()) {
//                volume = mModel.getMaxSoundVolume();
//            }
//
//            mModel.setCurSoundVolume(volume, true);
//        }
    }

    int currentB = 0;
    // 手势操作开始的亮度点
    private int mOldBrightness;

    private void setBrightness(float incremental) {
//        if (mModel != null) {
//            if (currentB == 0) {
//                mOldBrightness = getBrightness();
//                float bright = LetvApplication.getInstance().getBritness();
//                mOldBrightness = bright == 0 ? mOldBrightness : (int) (bright * 255);
//                currentB = mOldBrightness;
//            }
//            float brightness = (float) mOldBrightness / 255 + incremental;
//            LogInfo.log("fornia", "Brightness letvplaygest setBrightness:incremental:" + incremental + " brightness"
//                    + brightness);
//            if (brightness < 0) {
//                brightness = 0;
//            }
//
//            if (brightness > 1.0) {
//                brightness = 1.0f;
//            }
//            mModel.setBrightness(brightness);
//        }
    }

    public void onTouchEventUp() {
//        if (mModel != null) {
//            mModel.sendEvent(LiveRoomConstant.EVENT_TOUCH_EVENT_UP);
//        }
    }

    private void doSingleTapUp() {
//        if (mModel != null) {
//            mModel.doSingleTapUp();
//        }
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    /**
     * 完成手势走的调节声音和调节亮度的功能
     * e1是第一次down的ponter event
     * e2是当前滑动的pointer event
     */
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if (mIsPanorama) {
            return false;
        }

        // 直播半屏播放器不响应手势的滚动
//        if (mModel != null && !mModel.isFullScreen()) {
//            return false;
//        }

        int s = e2.getPointerCount();
        if (s == 2) {// 双指滑动
            offsetY += distanceY;
            if (offsetY > 0) {
                if (offsetY > doubleFingersUpCuttingValue * getHeight()) {// 向下
                    event = DOUBLE_FINGERS_UP;
                } else {// 距离不够，或者划回来就取消事件
                    event = NONE;
                }
            } else {
                if (offsetY < -doubleFingersDownCuttingValue * getHeight()) {// 向上
                    event = DOUBLE_FINGERS_DOWN;
                } else {// 距离不够，或者划回来就取消事件
                    event = NONE;
                }
            }
        } else if (s == 1) {// 单指滑动
            LogInfo.log("fornia", "Brightness letvplaygest distanceY:" + distanceY + "distanceX:" + distanceX);
            if (Math.abs(distanceY) > portraitLimitSlope * Math.abs(distanceX) && directionalLock != 2) {// 斜率判断，竖划
                directionalLock = 1;
                if (e2.getX() > (1 - bothSidesCuttingValue) * getWidth()) {// 右半屏幕上下滑动
                    LogInfo.log("fornia", "Brightness letvplaygest distanceY:" + distanceY + "distanceX:" + distanceX
                            + "!!!!!!!!!右屏上下");
                    rightProgerss += distanceY / getHeight();

                    setVolume(rightProgerss);

                    if (mCallbacks != null) {
                        mCallbacks.onRightScroll(rightProgerss);
                    }
                } else if (e2.getX() < bothSidesCuttingValue * getWidth()) {// 左半屏幕上下滑动
                    LogInfo.log("fornia", "Brightness letvplaygest distanceY:" + distanceY + "distanceX:" + distanceX
                            + "!!!!!!!!!");
                    leftProgress += distanceY / getHeight();
                    LogInfo.log("fornia", "Brightness letvplaygest leftProgress:" + leftProgress);

                    setBrightness(leftProgress);

                    if (mCallbacks != null) {
                        mCallbacks.onLeftScroll(leftProgress);
                    }
                } else if (e1.getX() > (middleCuttingValue - bothSidesCuttingValue) * getWidth()
                        && e1.getX() < (middleCuttingValue + bothSidesCuttingValue) * getWidth()) {
                    LogInfo.log("fornia", "Brightness letvplaygest distanceY:" + distanceY + "distanceX:" + distanceX
                            + "!!!!!!!!!else");
                    offsetY += distanceY;
//                    if (mCallbacks != null || mModel != null) {
//                        if (offsetY > bothSidesCuttingValue * getHeight()) {// 单指向上滑动
//                            event = SINGLE_FINGERS_UP;
//                        } else if (offsetY < -bothSidesCuttingValue * getHeight()) {// 单指向下滑动
//                            event = SINGLE_FINGERS_DOWN;
//                        }
//                    }
                }
            } else if (Math.abs(distanceY) < landscapeLimitSlope * Math.abs(distanceX) && directionalLock != 1) {// 斜率判断，横划
                directionalLock = 2;
                offsetX -= distanceX;

                landscapeProgress = offsetX / getWidth();

                if (mCallbacks != null) {
                    mCallbacks.onLandscapeScroll(landscapeProgress);
                }

                event = LANDSCAPE_SCROLL_FINISH;
            }
        }

        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        if (mCallbacks != null) {
            mCallbacks.onLongPress();
        }
    }

    public interface LetvPlayGestureCallBack {
        /**
         * 双指下划
         */
        void onDown();

        /**
         * 双指下划
         */
        void onDoubleFingersDown();

        /**
         * 双指上划
         */
        void onDoubleFingersUp();

        /**
         * 单击
         */
        void onSingleTapUp();

        /**
         * 双击
         */
        void onDoubleTap();

        /**
         * 右边上下滑动 变化总量
         */
        void onRightScroll(float incremental);

        /**
         * 左边上下滑动 变化总量
         */
        void onLeftScroll(float incremental);

        /**
         * 中间单指上滑
         */
        void onMiddleSingleFingerUp();

        /**
         * 中间单指下滑
         */
        void onMiddleSingleFingerDown();

        /**
         * 横向滑动 变化总量
         */
        void onLandscapeScroll(float incremental);

        /**
         * 横向滑动 变化总量
         */
        void onLandscapeScrollFinish(float incremental);

        /**
         * up事件，完成所有操作了
         */
        void onTouchEventUp();

        /**
         * 长按
         */
        void onLongPress();

        /**
         * 接触屏幕即出发，用于保持屏幕唤醒
         */
        void onTouch();

        int setOneFingertouchInfomation(float begin_x, float begin_y, float end_x, float end_y);

        int setTwoFingertouchInfomation(float begin_x0, float begin_y0, float begin_x1,
                                        float begin_y1, float end_x0, float end_y0, float end_x1,
                                        float end_y1);

        int setTwoScale(float scale);
    }
}
